﻿using Contracts;
using LPLS.PluginCommon;
using LPLS.PluginCommon.ModulePlugin;
using Prism.DryIoc;
using Prism.Ioc;
using Prism.Modularity;
using Shell.Views;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows;

namespace Shell
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : PrismApplication
    {
        protected override Window CreateShell()
        {
            return Container.Resolve<MainWindow>();
        }

        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
            // 注册共享服务
            containerRegistry.RegisterSingleton<INavigationRegistry, NavigationRegistry>();
            containerRegistry.RegisterSingleton<IModuleEventAggregator, ModuleEventAggregator>();

            /// 注册插件服务  数据库  暂时挂起
            RegisterSqlTypes(containerRegistry);
        }

        /// <summary>
        /// 注册SqlSugar类型
        /// </summary>
        /// <param name="containerRegistry"></param>
        private void RegisterSqlTypes(IContainerRegistry containerRegistry)
        {
            // 初始化数据库配置
            LPLS.DBServices.DatabaseConfig.InitDataBaseConfig();
            // 注册DBContext
            containerRegistry.RegisterInstance(new LPLS.DBEntities.DBContext(LPLS.DBServices.DatabaseConfig.ConfiguredDbContexts));

            // 使用反射自动注册服务
            var serviceTypes = Assembly.Load("LPLS.DBServices").GetTypes()
                .Where(t => t.IsClass && t.GetInterfaces().Any(i => i.Name == "I" + t.Name));

            foreach (var serviceType in serviceTypes)
            {
                var interfaceType = serviceType.GetInterfaces().First(i => i.Name == "I" + serviceType.Name);
                containerRegistry.Register(interfaceType, serviceType);
            }
        }

        protected override void ConfigureModuleCatalog(IModuleCatalog moduleCatalog)
        {
            base.ConfigureModuleCatalog(moduleCatalog);
            LoadModules(moduleCatalog);
        }


        /// <summary>
        /// 添加ViewModel 服务
        /// </summary>
        /// <param name="moduleCatalog"></param>
        private void LoadModules(IModuleCatalog moduleCatalog)
        {
            // 查找模块目录
            var modulesPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Modules");
            if (!Directory.Exists(modulesPath))
            {
                Directory.CreateDirectory(modulesPath);
                return;
            }

            // 加载所有模块DLL
            foreach (var dll in Directory.GetFiles(modulesPath, "*.dll"))
            {
                try
                {
                    var assembly = Assembly.LoadFrom(dll);
                    var moduleTypes = assembly.GetTypes()
                        .Where(t => (typeof(IModule).IsAssignableFrom(t) || typeof(ModuleBaseModule).IsAssignableFrom(t)) && !t.IsAbstract);

                    foreach (var type in moduleTypes)
                    {
                        moduleCatalog.AddModule(new ModuleInfo
                        {
                            ModuleName = type.Name,
                            ModuleType = type.AssemblyQualifiedName,
                            InitializationMode = InitializationMode.WhenAvailable
                        });
                    }
                }
                catch (Exception ex)
                {
                    // 记录模块加载错误
                    Console.WriteLine($"加载模块失败: {dll}, 错误: {ex.Message}");
                }
            }
        }

        protected override void OnInitialized()
        {
            base.OnInitialized();

            // 发布模块加载完成事件
            var eventAggregator = Container.Resolve<IModuleEventAggregator>();
            eventAggregator.PublishModulesLoaded();
        }


    }

    public class ConfigModel
    {
        public string ProjectID { get; set; }
        public string Version { get; set; }
    }
}